/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jivesoftware.smack.XMPPException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.fire8.dolphin.db.FriendDAO;
import com.fire8.dolphin.model.Friend;
import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.service.JaberClientService;
import com.fire8.dolphin.ui.chat.ChatActivity;
import com.fire8.dolphin.ui.imgcache.AsynLoad;
import com.fire8.dolphin.ui.more.RegisterActivity;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 用户信息显示页面
 * 显示全部问题
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class UserInfoActivity extends Activity
{
    private ProgressDialog progressDialog = null;
    
    private ImageView imgHead;
    private TextView tvUserName;
    private TextView tvPoint;
    private TextView tvUserTitle;
    private TextView tvRemark;
    
    //private Button btnAddPoint;//赠送鲜花
    private Button btnSendMessage;//发送消息
    private Button btnAnswerRecord;//回答记录
    private Button btnChatRecord;//聊天记录
    private View vLine1;//btnAddPoint下面的线
    private View vLine2;//btnAddFriend下面的线
    private View vLine3;//btnAnswerRecord下面的线
    
    private String from;//从哪个页面跳转过来的[回答页面(answer)、好友列表(friend)、用户列表(user)]
    private JaberClientService jaberClientService;
    private boolean success=false;
    
    private Bitmap bitmap;//用户头像
    private String userId;
//    private String account;
    private UserInfo userInfo;
    private FriendDAO friendDao;
    private AsynLoad anseylodar;
    private DolphinApplication app;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_manage);
        app = (DolphinApplication)getApplication();
        getElement();
        anseylodar=new AsynLoad();//异步加载头像
        userId = getIntent().getStringExtra("userId");
        from = getIntent().getStringExtra("from");
        LogUtil.d("userId:"+userId);
        LogUtil.d("from:"+from);
        setElementEvent();
        jaberClientService = JaberClientService.getInstance();
        friendDao = new FriendDAO(this);
    }
    
    private void getElement()
    {
        
        imgHead = (ImageView)findViewById(R.id.img_head);
        tvUserName = (TextView)findViewById(R.id.tv_user_name);
        tvPoint = (TextView)findViewById(R.id.tv_point);
        tvUserTitle = (TextView)findViewById(R.id.tv_user_title);
        tvRemark = (TextView)findViewById(R.id.tv_user_remark);
        //btnAddPoint = (Button)findViewById(R.id.btn_add_point);
        btnSendMessage = (Button)findViewById(R.id.btn_send_message);
        btnAnswerRecord = (Button)findViewById(R.id.btn_answer_record);
        btnChatRecord = (Button)findViewById(R.id.btn_chat_record);
        vLine1 = (View)findViewById(R.id.v_line1);
        vLine2 = (View)findViewById(R.id.v_line2);
        vLine3 = (View)findViewById(R.id.v_line3);
    }
    
    private void setElementEvent()
    {
        if("user".equals(from))
        {
            //用户列表跳转过来，显示加好友和回答记录两个按钮
            btnSendMessage.setVisibility(View.VISIBLE);
            //btnAnswerRecord.setVisibility(View.VISIBLE);
            //vLine2.setVisibility(View.VISIBLE);
        }else if("answer".equals(from))
        {
            //从回答记录跳过来，显示赠送鲜花、加为好友、查看回答记录三个按钮
            //btnAddPoint.setVisibility(View.VISIBLE);
            btnSendMessage.setVisibility(View.VISIBLE);
            
            //btnAnswerRecord.setVisibility(View.VISIBLE);
            //vLine1.setVisibility(View.VISIBLE);
            //vLine2.setVisibility(View.VISIBLE);
        }else
        {
            //否则，就是从好友列表跳转过来，显示回答记录、聊天记录两个按钮
            //这几个功能留第二期再实现
            //btnAnswerRecord.setVisibility(View.VISIBLE);
            //btnChatRecord.setVisibility(View.VISIBLE);
            //vLine3.setVisibility(View.VISIBLE);
        }
        
        btnSendMessage.setOnClickListener(new OnButtonListener());
        //btnAddPoint.setOnClickListener(new OnButtonListener());
    }
    
    class OnButtonListener implements OnClickListener
    {

        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.btn_send_message:
                    //
                    //检查用户是否已登录
                    if(StringUtil.isEmpty(app.getAccount()))
                    {
                        //未登录，显示提示信息
                        //Toast.makeText(UserInfoActivity.this, "注册或登录后才可以发消息", Toast.LENGTH_LONG).show();
                        AlertDialog alert = new AlertDialog.Builder(UserInfoActivity.this)   
                        .setTitle("温馨提示")   
                        .setIcon(R.drawable.logo_n)   
                        .setMessage("需要注册或登录才可以发消息，现在需要注册吗？")   
                        .setPositiveButton("再在注册",   
                                new DialogInterface.OnClickListener() {   
                                    public void onClick(DialogInterface dialog,   
                                            int which) {   
                                        //跳转到注册页面
                                        Intent intent = new Intent(UserInfoActivity.this,RegisterActivity.class);
                                        startActivity(intent);
                                        UserInfoActivity.this.finish();
                                        return;
                                    }   
                                })   
                        .setNegativeButton("稍候再说",   
                                new DialogInterface.OnClickListener() {   
                                    public void onClick(DialogInterface dialog,   
                                            int which) {   
                                        dialog.cancel();   
                                        return;
                                    }   
                                }).show();   
                        
                    }else
                    {
                        if(!UserInfo.USER_TYPE_SERVER.equals(app.getUserType()))
                        {
                            Toast.makeText(UserInfoActivity.this, "对不起，只有咨询师才能与用户交谈", Toast.LENGTH_LONG).show();
                            return;
                        }
                        //保存到会话列表
                        if(bitmap != null)
                        {
                            app.saveFile(bitmap, String.valueOf(userInfo.getUserId()));
                        }
                        friendDao.add(userInfo);
                        //加对方为好友
                        new AddFriendTask().execute(app.getUserId(),userInfo.getAccount());
                        //跳转到聊天页面
                        Intent intent = new Intent(UserInfoActivity.this,ChatActivity.class);
                        intent.putExtra("userId", userId);
                        intent.putExtra(Friend.C_USER_NAME, userInfo.getUserName());
                        //intent.putExtra(Friend.C_USER_HEAD, map.get(Friend.C_USER_HEAD));
                        intent.putExtra(Friend.C_ACCOUNT, userInfo.getAccount());
                        //intent.putExtra("from", "user");
                        startActivity(intent);
                        //半闭用户信息页面
                        UserInfoActivity.this.finish();
                    }
                    break;
                case R.id.btn_add_point:
                    
                    break;
                default:
                    break;
            }
        }
        
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        //页面打开时，请求用户数据并显示出来
        progressDialog = ProgressDialog.show(this, "请稍等...", "正在加载用户数据...", true);
        new GetUserTask().execute(userId);
    }
    
    
    
    class AddFriendTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            if(!RequestUtils.getInstall().isConnect(UserInfoActivity.this))
            {
                return "网络不可用";
            }
            try
            {
                //加为好友
                LogUtil.d("加好友："+params[0]);
                jaberClientService.requestAddFriend(params[1]);
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",params[0]));
                param.add(new BasicNameValuePair("friendAccount",params[1]));
                String json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"user/addFriend.php", param);
                LogUtil.d(json);
            }
            catch (XMPPException e)
            {
                LogUtil.e("", e);
                return "添加好友失败";
            }
            
            return "";
            
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(!success)
            {
                //Toast.makeText(UserInfoActivity.this, result, Toast.LENGTH_LONG).show();
                //progressDialog.dismiss();
                return;
            }
            //关闭进度条窗口
            //progressDialog.dismiss();      
        }
        
    }
    //获得用户信息
    class GetUserTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            if(!RequestUtils.getInstall().isConnect(UserInfoActivity.this))
            {
                return "网络不可用";
            }
            
            String json = null;
            try
            {
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",params[0]));
                json = RequestUtils.getInstall().getHttpJson(DolphinApplication.URL+"user/getUserInfo.php", param);
                LogUtil.d(json);
                success=true;
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
                return "请求失败，请稍候再试";
            }
            return json;
            
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(!success)
            {
                progressDialog.dismiss();
                UserInfoActivity.this.finish();
                Toast.makeText(UserInfoActivity.this, result, Toast.LENGTH_LONG).show();
                return;
            }
            try
            {
                JSONObject data = new JSONObject(result);
                String msgCode = data.getString("msgCode");
                String desc = data.getString("desc");
                if("1".equals(msgCode))
                {
                    JSONObject object = data.getJSONObject("msgBody");
                    tvUserName.setText(object.getString("userName"));
                    tvPoint.setText(object.getString("point"));
                    tvUserTitle.setText(object.getString("userTitle"));
                    tvRemark.setText(object.getString("remark"));
                    imgHead.setTag(RequestUtils.IMG_URL+object.getString("userId")+".jpg");
                    bitmap = anseylodar.showimgAnsy(imgHead,RequestUtils.IMG_URL+object.getString("userId")+".jpg");//异步加载图片
                    userInfo = new UserInfo();
                    userInfo.setUserId(Integer.valueOf(object.getString("userId")));
                    userInfo.setUserName(object.getString("userName"));
                    userInfo.setAccount(object.getString("account"));
                    userInfo.setHeadPic(object.getString("headPic"));
                    userInfo.setPoint(Integer.valueOf(object.getString("point")));
                    userInfo.setRemark(object.getString("remark"));
                    userInfo.setUserTitle(object.getString("userTitle"));
                }else
                {
                    Toast.makeText(UserInfoActivity.this, desc, Toast.LENGTH_LONG).show();
                    LogUtil.d(desc);
                    UserInfoActivity.this.finish();
                }      
            }
            catch (Exception e)
            {
                LogUtil.e("" ,e);
            }
            //关闭进度条窗口
            progressDialog.dismiss();      
        }
        
    }
}
